package com.block.datapush.form.item;

import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.SecureUtil;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.block.common.service.LogFactory;
import com.block.datapush.form.service.IFormPushHandle;
import com.block.datapush.form.item.util.HaoHuiTuiUtil;
import com.block.datapush.model.dto.FormPushResultDTO;
import com.block.db.entity.FormInfo;
import com.block.db.entity.FormInfoHis;
import com.block.db.entity.MemberExtInfo;
import org.slf4j.Logger;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

@Service
public class HaoHuiTuiPushHandleService implements IFormPushHandle {

    private static final Logger log = LogFactory.getCommLog();

    @Override
    public boolean queryMatchResult(FormInfo formInfo, MemberExtInfo memberExtInfo) {
        try {
            String queryUrl = StrUtil.format(formInfo.getQueryUrl(), formInfo.getApiKey());
            String mobileMd5 = SecureUtil.md5(memberExtInfo.getMobile()).toUpperCase();

            Map<String, Object> bizMap = new HashMap<>();
            bizMap.put("md5Phone", mobileMd5);
            bizMap.put("timestamp", String.valueOf(System.currentTimeMillis()));

            String sign = HaoHuiTuiUtil.signParam(bizMap, formInfo.getApiSecret());
            bizMap.put("sign", sign);

            String content = HaoHuiTuiUtil.encrypt(JSON.toJSONString(bizMap), formInfo.getPubKey());

            Map<String, Object> paramMap = new HashMap<>();
            paramMap.put("version", "1.0");
            paramMap.put("channelCode", formInfo.getApiKey());
            paramMap.put("content", content);

            log.info("【好会推】撞库开始【queryUrl】{}【bizMap】{}", queryUrl,  JSON.toJSONString(bizMap));
            String response = HttpUtil.createPost(queryUrl)
                    .body(JSON.toJSONString(paramMap))
                    .execute().body();
            log.info("【好会推】撞库结束【result】{}", response);

            JSONObject responseObject = JSON.parseObject(response);
            JSONObject head = responseObject.getJSONObject("head");
            String body = responseObject.getString("body");
            String returnCode = head.getString("returnCode");

            if (StrUtil.equals(body, "100") ) {
                return true;
            }
            return false;
        } catch (Exception exception) {
            exception.printStackTrace();
        }
        return false;
    }

    @Override
    public FormPushResultDTO pushMemberInfo(FormInfo formInfo, MemberExtInfo memberExtInfo, String orderNo, JSONObject extObject) {
        FormPushResultDTO pushResultDTO = new FormPushResultDTO();
        pushResultDTO.setOrderNo(orderNo);
        try {

            String requestUrl = StrUtil.format(formInfo.getRequestUrl(), formInfo.getApiKey());

            Map<String, Object> bizMap = new HashMap<>();
            bizMap.put("channelUserId", String.valueOf(memberExtInfo.getUid()));
            bizMap.put("timestamp", String.valueOf(System.currentTimeMillis()));
            bizMap.put("name", memberExtInfo.getUsername());
            bizMap.put("phone", memberExtInfo.getMobile());

            String sign = HaoHuiTuiUtil.signParam(bizMap, formInfo.getApiSecret());
            bizMap.put("sign", sign);

            bizMap.put("ip", memberExtInfo.getReqIp());
            bizMap.put("osType", "android");
            bizMap.put("idCardNo", memberExtInfo.getIdCard());
            bizMap.put("sex", memberExtInfo.getSex()==1?"SM":"SW");
            bizMap.put("age", memberExtInfo.getAge());

            bizMap.put("cityCode", memberExtInfo.getCityCode());
            bizMap.put("profession", "A");
            bizMap.put("payType", "D");
            bizMap.put("workingAge", "H");
            bizMap.put("loanTime", "P");
            bizMap.put("education", "X");

            bizMap.put("loan", HaoHuiTuiUtil.getLoanAmount(memberExtInfo.getLoanAmount()));
            bizMap.put("socialSecurity", HaoHuiTuiUtil.getSheBao(memberExtInfo.getSocialInsurance()));
            bizMap.put("providentFund", HaoHuiTuiUtil.getGjj(memberExtInfo.getGjj()));
            bizMap.put("estate", HaoHuiTuiUtil.getHouse(memberExtInfo.getHouse()));

            String estateType = HaoHuiTuiUtil.getHouseType(memberExtInfo.getHouse());
            if (StrUtil.isNotEmpty(estateType)){
                bizMap.put("estateType", estateType);
            }

            bizMap.put("car", HaoHuiTuiUtil.getCar(memberExtInfo.getCar()));
            String carType = HaoHuiTuiUtil.getCarType(memberExtInfo.getCar());
            if (StrUtil.isNotEmpty(carType)){
                bizMap.put("carType", carType);
            }

            String carAmount = HaoHuiTuiUtil.getCarAmount(memberExtInfo.getCar());
            if (StrUtil.isNotEmpty(carAmount)){
                bizMap.put("carAmount", carAmount);
            }

            bizMap.put("personalInsurance", HaoHuiTuiUtil.getBaoDan(memberExtInfo.getInsurance()));
            bizMap.put("creditScore", HaoHuiTuiUtil.getZhiMa(memberExtInfo.getZhimaScore()));
            bizMap.put("wldLoan", "UU");
            bizMap.put("creditCard", "WW");
            bizMap.put("creditRecord", HaoHuiTuiUtil.getYuQi(memberExtInfo.getYuqi()));
            bizMap.put("jdWhite", HaoHuiTuiUtil.getBaiTiao(memberExtInfo.getBaitiao()));
            bizMap.put("aliBei", HaoHuiTuiUtil.getHuaBei(memberExtInfo.getHuabei()));


            String content = HaoHuiTuiUtil.encrypt(JSON.toJSONString(bizMap), formInfo.getPubKey());

            Map<String, Object> paramMap = new HashMap<>();
            paramMap.put("version", "1.0");
            paramMap.put("channelCode", formInfo.getApiKey());
            paramMap.put("content", content);

            log.info("【好会推】导单开始【requestUrl】{}【bizMap】{}", requestUrl,  JSON.toJSONString(bizMap));
            String result = HttpUtil.createPost(requestUrl)
                    .body(JSON.toJSONString(paramMap))
                    .execute().body();
            log.info("【好会推】导单结束【result】{}", result);

            JSONObject resultObject = JSON.parseObject(result);

            JSONObject head = resultObject.getJSONObject("head");
            String returnCode = head.getString("returnCode");
            String returnMessage = head.getString("returnMessage");

            pushResultDTO.setResult(result);
            pushResultDTO.setCode(String.valueOf(returnCode));
            pushResultDTO.setMessage(returnMessage);
            pushResultDTO.setParamContent(JSON.toJSONString(bizMap));

            if (StrUtil.equals(returnCode, "000000")){
                JSONObject body = resultObject.getJSONObject("body");
                boolean resultInfo = body.getBoolean("result");
                if (resultInfo){
                    pushResultDTO.setSuccess(true);
                }else{
                    pushResultDTO.setSuccess(false);
                }
            }else{
                pushResultDTO.setSuccess(false);
            }
            return pushResultDTO;
        }catch (Exception exception){
            exception.printStackTrace();
        }
        return pushResultDTO;
    }

    @Override
    public void afterPushHandle(FormInfoHis formInfoHis) {

    }


    public static void main(String[] args) {

//        "690A4F1C0BB3CC3C7FB01BCF0AA0DD04"

        String content = "lblbom4qoUqWCRpLxpjgPPcahBCYEYUDchbxwQyLU+KNZjLvOULsnWCucIFCZplwWJMM+ptqo8ZeA+iqLUH17EFycipC/rcMomynJ/E55DfIry3rZq56z5uKhSN+mv8jSf54C8QLEcLBBELykIgDazaxsrqMZ3C3nBYQYCGgFmIXRJUROSxnhxnk26Uh6T7W7V0EbEXqHqqIfMlZMhe3Jjr/8DlSSaAvojMHddUtcMdJ/ICAXA13Lg9FljECQiD9GA1cyAHyO0WWckAR391VDYxZHZHyt82Z8LtBlyybvUiZXWrwYuYpiBDuLrh0RxG10+s+lIm/bOQay3D0b2viz8opGkoAU3OyHrRMRaP9Mge+Wv0FyTi82mQW783RDNakCxtVYkWH4UlA9frVpSNA75UDbF0XpWXiMZ1ypr/jl8h2dmmOVZyt9fsjiFMf3t9AEOdNvZaXX4hMaYOTrpbNFtrYeY6OuW0BsiuOnyiQGwooB4FOyMUsnHENOjmdGojat3b/INGGX6mBKi8SmyfCOIGN97TWyIZ1StvybhVgHvNV/b3JfZGl/lXcphnNh7ImP8ASUeCvvWpDcBcGpAESt7do/9xtAHHZcfOx7HC8302cSJ3/rt9aq3QNn1qOBUbF/Z7JbqlgQewFPI0IkogbkdJVLv29uzHMc8IBbGk5pE4Z8MJbFzA9zqe5VZIIoZQK5ZQn85M8xbFp6t6rGMFlgQqwimLU6Xhwajz8rjjKx9w=";

        String aesKey = "sonGzsx3DgID57CBzM3QHA==";

        String decrypt = HaoHuiTuiUtil.decrypt(content, aesKey);

        System.out.println(decrypt);

        Map<String, Object> bizMap = JSON.parseObject(decrypt, Map.class);

        System.out.println();
        System.out.println();
        System.out.println(JSON.toJSONString(bizMap));

        String sign = (String)bizMap.get("sign");
        bizMap.remove("sign");

        System.out.println();
        System.out.println();
        System.out.println(sign);
        System.out.println();

        String jskd72h6dks6 = HaoHuiTuiUtil.signParam(bizMap, "jskd72h6dks6");

        System.out.println(jskd72h6dks6);

    }

}
